package com.youyoulong.framework.util.filter;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class ResourceContextFilter extends OncePerRequestFilter {

	// private final String _resourceViewerPath = "/static/viewer";
	private String actionSuffix = ".do";
	private String pathPerfix = "/static/view";
	private String freemarkerSuffix = ".html";

	public void setActionSuffix(String actionSuffix) {
		this.actionSuffix = actionSuffix;
	}

	public void setPathPerfix(String pathPerfix) {
		this.pathPerfix = pathPerfix;
	}

	public void setFreemarkerSuffix(String freemarkerSuffix) {
		this.freemarkerSuffix = freemarkerSuffix;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String url = request.getRequestURI().toString();

		// <!--如果是html直接跳转-->
		if (url.indexOf(pathPerfix) > -1) {
			proccessViewer(request, response, filterChain, getResourcePath(url));
		} else {
			filterChain.doFilter(request, response);
		}
	}

	private void proccessViewer(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain,
			String filePath) throws ServletException, IOException {
		try {
			if (filePath.indexOf(freemarkerSuffix) > -1) {
				proccessHtml(request, response, filterChain); /// 对html要进行特殊处理
			} else {
				if (isImages(filePath)) {
					int index = filePath.lastIndexOf(".");
					if (index < 0) {
						response.setHeader("Content-Type", "image/gif");
					} else {
						if (index == filePath.length() - 1) {
							response.setHeader("Content-Type", "image/gif");
						} else {
							response.setHeader("Content-Type", "image/" + filePath.substring(index + 1));
						}
					}
				} else if (filePath.indexOf(".js") > -1) {
					response.setHeader("Content-Type", "text/javascript");
				} else if (filePath.indexOf(".css") > -1) {
					response.setHeader("Content-Type", "text/css");
				} else {
					response.setHeader("Content-Type", "*/*");
				}

				ServletOutputStream sos = response.getOutputStream();
				BufferedInputStream fin = new BufferedInputStream(
						new FileInputStream(this.getClass().getResource(filePath).getFile()));
				byte[] content = new byte[1024];
				int length;
				while ((length = fin.read(content, 0, content.length)) != -1) {
					sos.write(content, 0, length);
				}
				fin.close();
				sos.flush();
				sos.close();
			}
		} catch (Exception e) {
			filterChain.doFilter(request, response);
		}
	}

	private void proccessHtml(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String url = request.getRequestURI().toString();
		int index = url.indexOf(pathPerfix);
		int indexHtml = url.indexOf(freemarkerSuffix);
		String lastString = url.substring(indexHtml + freemarkerSuffix.length());
		String path = url.substring(index + pathPerfix.length(), indexHtml);
		path = "/viewer/" + path.replace("/", ".") + actionSuffix + lastString;
		RequestDispatcher rd = request.getRequestDispatcher(path);
		rd.forward(request, response);
	}

	private String getResourcePath(final String url) {
		int index = url.indexOf(pathPerfix);
		return "/web/view" + url.substring(index).replace(pathPerfix, "");
	}

	private boolean isImages(String fileName) {
		try {
			if (ImageIO.read(new File(this.getClass().getResource(fileName).getFile())) == null) {
				return false;
			}
		} catch (Exception ex) {
			return false;
		}
		return true;
	}

}
